<template>
  <div v-loading="importIng" class="flex-column h-1 flex-1" style="min-height: 400px">
    <!-- 网段基本信息 -->
    <div v-if="type !== 'add'" class="flex flex-wrap segment-detail">
      <div class="w-50">
        <span class="title-label">{{ $t('SEGMENT_NAME') }}:</span>
        <el-input
          v-if="type === 'mod'"
          v-model.trim="formData.segmentName"
          class="flex-1 mr-20"
          maxlength="100"
        />
        <span v-else>
          {{ formData.segmentName }}
        </span>
      </div>
      <div class="w-50">
        <span class="title-label">{{ $t('CABLE_NAME') }}:</span>
        <span> {{ formData.cable ? formData.cable.cableName : '--' }}</span>
      </div>
      <div class="w-50">
        <span class="title-label">{{ $t('A_END_REGIONAL_STATION_NAME') }}:</span>
        <span> {{ formData.startStationName }}</span>
      </div>
      <div class="w-50">
        <span class="title-label">{{ $t('Z_END_REGIONAL_STATION_NAME') }}:</span>
        <span> {{ formData.endStationName }}</span>
      </div>
      <div class="w-50">
        <span class="title-label">{{ $t('A_END_ROOM_NAME') }}:</span>
        <span> {{ formData.startRoomName }}</span>
      </div>
      <div class="w-50">
        <span class="title-label">{{ $t('Z_END_ROOM_NAME') }}:</span>
        <span> {{ formData.endRoomName }}</span>
      </div>
      <div class="w-50">
        <span class="title-label">{{ $t('ANODE') }}:</span>
        <span> {{ formData.startNode.nodeName }}</span>
      </div>
      <div class="w-50">
        <span class="title-label">{{ $t('ZNODE') }}:</span>
        <span> {{ formData.endNode.nodeName }}</span>
      </div>
    </div>
    <div v-if="type !== 'view'" class="flex justify-between align-center mb-10">
      <div>
        <span class="text-warning">{{ $t('ALLOW_ADD_SEGMENT_AT_MOST') + maxlength }}</span>
        <span class="text-warning ml-50">{{
          $t('CHANNELS_ADDED') + formData.segmentChannelList.length
        }}</span>
      </div>
      <el-button
        v-if="type !== 'view'"
        slot="trigger"
        size="mini"
        type="primary"
        @click="importVisible = true"
      >{{ $t('IMPORT') }}</el-button>
    </div>
    <div class="flex justify-end mb-10">
      <el-button v-if="type === 'view'" class="ml-10" size="mini" @click="exportClick">
        {{ $t('EXPORT') }}
      </el-button>
    </div>
    <div v-show="showSelect" id="selectDiv">
      <el-select
        id="select"
        ref="testSelect"
        v-model="activeData.selectedId"
        size="mini"
        filterable
        @change="selectChange"
        @visible-change="visibleChange"
      >
        <el-option
          v-for="port in activeList"
          :key="port.portId || port.fiberId"
          :label="port.bizName || port.fiberName || '--'"
          :value="port.portId || port.fiberId"
          :disabled="portDisable(port)"
        />
      </el-select>
    </div>
    <el-table
      ref="channelTable"
      :data="formData.segmentChannelList"
      size="mini"
      min-height="300px"
      height="100%"
      row-key="channelId"
      border
      align="center"
      @cell-click="cellClick"
    >
      <template slot="empty">
        <NullData />
      </template>
      <el-table-column type="index" :label="$t('SEQUENCE')" :width="resetSize(60)" />
      <!-- 通道状态 -->
      <el-table-column v-if="type !== 'add'" :label="$t('CHANNEL_STATUS')">
        <template v-slot="scope">
          {{ dictMap.CHANNEL_STATUS[scope.row.status] }}
        </template>
      </el-table-column>
      <el-table-column v-if="type !== 'add'" :label="$t('LINK_LOSS')" width="150" prop="loss">
        <template v-slot="scope">
          {{
            scope.row.linkLoss > 990000
              ? '--'
              : changeDecimal(scope.row.linkLoss, 3)
          }}
        </template>
      </el-table-column>
      <!-- A端节点信息 -->
      <el-table-column :label="formData.startNode.nodeName" :render-header="tableRenderHeader">
        <el-table-column
          v-if="
            formData.startNode.nodeCategory !== 'LIGHT_SPLIT' &&
              formData.startNodeCategory !== 'TRANSPORT'
          "
          :label="$t('A_EEND_PORT')"
          show-overflow-tooltip
        >
          <template v-slot="scope">
            {{ getPortName(aAllPortList, scope.row.startPortId) }}
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('Z_EEND_PORT')"
          :show-overflow-tooltip="type === 'view'"
          prop="startPort"
        >
          <template v-slot="scope">
            <span v-if="type === 'view'">
              {{ getPortName(aAllPortList, scope.row.startPortId, 'bizName') }}
            </span>
            <div v-else class="select-holder flex" :class="getCellDisabled(scope.row)">
              <span class="flex-1">{{
                getPortName(aAllPortList, scope.row.startPortId, 'bizName')
              }}</span>
              <i class="el-icon-arrow-down" />
            </div>
          </template>
        </el-table-column>
      </el-table-column>
      <!-- 光缆信息 -->
      <el-table-column
        v-if="formData.cableId"
        :label="formData.cable.cableName"
        :render-header="tableRenderHeader"
      >
        <el-table-column
          :label="$t('FIBER_CORE')"
          :show-overflow-tooltip="type === 'view'"
          prop="fiber"
        >
          <template v-slot="scope">
            <span v-if="type === 'view'">
              {{ scope.row.fiber ? scope.row.fiber.fiberName : '' }}
            </span>
            <div v-else class="select-holder flex" :class="getCellDisabled(scope.row)">
              <span class="flex-1">{{ scope.row.fiber ? scope.row.fiber.fiberName : '' }}</span>
              <i class="el-icon-arrow-down" />
            </div>
          </template>
        </el-table-column>
      </el-table-column>
      <!-- Z端节点信息 -->
      <el-table-column :label="formData.endNode.nodeName" :render-header="tableRenderHeader">
        <el-table-column
          :label="$t('A_EEND_PORT')"
          :show-overflow-tooltip="type === 'view'"
          prop="endPort"
        >
          <template v-slot="scope">
            <span v-if="type === 'view'">
              {{ getPortName(zAllPortList, scope.row.endPortId, 'bizName') }}
            </span>
            <div v-else class="select-holder flex" :class="getCellDisabled(scope.row)">
              <span class="flex-1">{{
                getPortName(zAllPortList, scope.row.endPortId, 'bizName')
              }}</span>
              <i class="el-icon-arrow-down" />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="
            formData.endNodeCategory !== 'LIGHT_SPLIT' && formData.endNodeCategory !== 'TRANSPORT'
          "
          :label="$t('Z_EEND_PORT')"
          show-overflow-tooltip
        >
          <template v-slot="scope">
            {{ getPortName(zAllPortList, scope.row.endPortId) }}
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column v-if="type !== 'view'" :label="$t('OPERATE')" class-name="operate-cell" :width="resetSize(80)">
        <template v-slot="scope">
          <el-button
            type="text"
            size="mini"
            icon="el-icon-plus"
            @click="addChannel(scope.$index)"
          />
          <el-button
            :disabled="scope.row.status && scope.row.status !== 'IDLE'"
            type="text"
            size="mini"
            icon="el-icon-minus"
            @click="del(scope.$index)"
          />
        </template>
      </el-table-column>
    </el-table>
    <!--导入引导-->
    <import-boot
      :visible="importVisible"
      @exportClick="exportClick"
      @ImportClick="importClick"
      @import-close="importVisible = false"
    >
      <template #notice>
        <div>
          {{ $t('BEFORE_IMPORTING_PLEASE') }}
          <span class="exportClick" @click="templateExportClick">
            {{ $t('EXPORT_TEMPLATE') }}
          </span>
          {{ $t('EDIT_BEFORE_IMPORT') }}
        </div>
        <div class="font-mini text-danger">
          <i class="el-icon-warning-outline" />
          {{ $t('ONLY_IMPORT_NEW') }}
        </div>
      </template>
    </import-boot>
  </div>
</template>
<script>
  import Sortable from 'sortablejs'
  import { mapGetters } from 'vuex'
  import nodeApi from '@/api/oen/NodeApi'
  import CableFiberApi from '@/api/oen/CableFiberApi'
  import clusterApi from '@/api/afs/ClusterApi'
  import OperateLogApi from '@/api/system/OperateLogApi.js'
  import linkTestPlan from '@/api/oen/LinkTestPlan'
  import { changeDecimal, tableRenderHeader } from '@/utils/common'
  import segmentMixin from '@/mixin/segmentMixin'
  import ImportBoot from '@/components/ImportBoot'

  export default {
    components: { ImportBoot },
    mixins: [segmentMixin],
    props: {
      type: {
        type: String,
        default: ''
      },
      formData: {
        type: Object,
        default: () => {}
      },
      step: {
        type: Number,
        default: 1
      },
      oldChannelList: {
        type: Array,
        default: () => []
      }
    },
    data() {
      return {
        showChannelList: false,
        aPortList: [],
        zPortList: [],
        aAllPortList: [],
        zAllPortList: [],
        cableFiberList: [],
        changeDecimal: changeDecimal,
        importVisible: false,
        importIng: false,
        activeData: {
          selectedId: '',
          key: ''
        },
        activeList: [],
        showSelect: false
      }
    },
    computed: {
      ...mapGetters(['baseRegionList', 'dictMap', 'getUserId', 'getUser']),
      // 最多添加通道数量
      maxlength() {
        return Math.min(
          this.aPortList.length,
          this.zPortList.length,
          this.formData.cableId ? this.cableFiberList.length : 99999
        )
      },
      channelItem() {
        return {
          // 端口可选的状态
          statusOptions: [
            {
              label: this.$t('CHANNEL_STATUS_IDLE'),
              value: 'IDLE'
            }
          ],
          status: 'IDLE',
          startPortId: '',
          fiberId: '',
          endPortId: '',
          linkLoss: 999999
        }
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.addScrollLinster()
        this.type !== 'view' && this.rowDrop()
      })
    },
    methods: {
      rowDrop() {
        const el = this.$refs.channelTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
        this.sortable = Sortable.create(el, {
          ghostClass: 'sortable-ghost',
          setData: function(dataTransfer) {
            dataTransfer.setData('Text', '')
          },
          onEnd: evt => {
            const targetRow = this.formData.segmentChannelList.splice(evt.oldIndex, 1)[0]
            this.formData.segmentChannelList.splice(evt.newIndex, 0, targetRow)
          }
        })
      },
      getCellDisabled(row) {
        const oldRow = this.oldChannelList.find(i => i.channelId === row.channelId)
        return row.status === 'MAIN' ||
          row.status === 'BACKUP' ||
          (oldRow && oldRow.status !== row.status)
          ? 'disabled'
          : ''
      },
      getStatusDisabled(row) {
        const oldRow = this.oldChannelList.find(i => i.channelId === row.channelId)
        return (
          (oldRow &&
            (oldRow.startPortId !== row.startPortId ||
              oldRow.endPortId !== row.endPortId ||
              oldRow.fiberId !== row.fiberId)) ||
          !oldRow ||
          this.type === 'view' ||
          row.status === 'MAIN' ||
          row.status === 'BACKUP'
        )
      },
      tableRenderHeader(h, data) {
        return tableRenderHeader(h, data)
      },
      addScrollLinster() {
        const that = this
        console.log(this.$refs.channelTable)
        const selectWrap = this.$refs.channelTable.$el.querySelector('.el-table__body-wrapper')
        selectWrap.addEventListener('scroll', function() {
          that.selectBlur()
        })
        document.querySelector('.el-dialog__body').addEventListener('scroll', function() {
          that.selectBlur()
        })
        document.querySelector('.segment-dialog').addEventListener('scroll', function() {
          that.selectBlur()
        })
      },
      cellClick(row, column, cell, event) {
        this.showSelect = false
        this.activeList = []
        if (row.status === 'MAIN' || row.status === 'BACKUP') return
        const oldRow = this.oldChannelList.find(i => i.channelId === row.channelId)
        if (oldRow && oldRow.status !== row.status) return
        this.activeData = row
        console.log('this.activeData', this.activeData)
        if (column.property === 'startPort') {
          this.activeList = this.aPortList
          this.activeData.selectedId = row.startPortId
        }
        if (column.property === 'endPort') {
          this.activeList = this.zPortList
          this.activeData.selectedId = row.endPortId
        }
        if (column.property === 'fiber') {
          this.activeList = this.cableFiberList
          this.activeData.selectedId = row.fiberId
        }
        this.activeData.key = column.property
        if (this.activeList.length === 0 || this.type === 'view') return
        this.$nextTick(() => {
          const selectDiv = document.getElementById('selectDiv')
          const cellbox = cell.querySelector('.cell')
          selectDiv.style.top = cellbox.getBoundingClientRect().top + 'px'
          selectDiv.style.left = cellbox.getBoundingClientRect().left + 'px'
          selectDiv.style.width = cellbox.clientWidth + 'px'
          this.$refs.testSelect.toggleMenu()
          this.showSelect = true
          this.$nextTick(() => {
            document.getElementById('select').focus()
          })
        })
      },
      selectBlur() {
        document.getElementById('select').blur()
        this.$refs.testSelect && this.$refs.testSelect.blur()
        this.$nextTick(() => {
          this.showSelect = false
        })
      },
      visibleChange(data) {
        console.log('visibleChange', data)
        if (data === false) {
          this.selectBlur()
        }
      },
      selectChange(id) {
        this.activeData[this.activeData.key + 'Id'] = id
        this.$set(
          this.activeData,
          this.activeData.key,
          this.activeList.find(i => i.fiberId === id || i.portId === id)
        )
        this.selectBlur()
      },
      refresh() {
        if (this.type === 'add') {
          this.formData.segmentChannelList = [{ ...this.channelItem }]
        }
        this.getPortList(this.formData.startNodeId, 'a')
        this.getPortList(this.formData.endNodeId, 'z')
        this.getCableFiberList()
        this.$nextTick(() => {
          this.showChannelList = true
        })
      },
      getPortName(allPortList, portId, key = 'connPortName') {
        const portData = allPortList.find(i => i.portId === portId)
        return portData ? portData[key] : '--'
      },
      portDisable(port) {
        const key = this.activeData.key
        const keyId = key + 'Id'
        let odfDisable = false
        if (port.deviceType === 'ODF') {
          const list = this.formData.segmentChannelList.filter(i => i[key])
          const firstChannel = list[0]
          const type =
            firstChannel && firstChannel[key] ? firstChannel[key].portName.split('-').pop() : ''
          if (list.length === 1 && firstChannel[keyId] === this.activeData[keyId]) {
            odfDisable = false
          } else {
            odfDisable = !port.portName.includes(type)
          }
        }
        return (
          odfDisable ||
          this.formData.segmentChannelList.some(i => {
            if (this.formData.startNodeId !== this.formData.endNodeId) {
              return i[keyId] === port.portId || i[keyId] === port.fiberId
            } else {
              return (
                i.startPortId === port.portId ||
                // i.startPortId === port.connPortId ||
                i.endPortId === port.portId ||
                // i.endPortId === port.connPortId ||
                i.fiberId === port.fiberId
              )
            }
          })
        )
      },
      // 向下添加通道
      addChannel(index) {
        if (this.formData.segmentChannelList.length >= this.maxlength) {
          this.$message.error(this.$t('ALLOW_ADD_SEGMENT_AT_MOST') + this.maxlength)
          return
        }
        this.formData.segmentChannelList.splice(index + 1, 0, {
          ...this.channelItem
        })
      },
      // 删除通道(已开通业务的通道不能删除)
      del(index) {
        if (this.formData.segmentChannelList.length === 1) {
          this.$message(this.$t('CAN_NOT_DEL'))
          return false
        } else {
          const currentChannel = this.formData.segmentChannelList[index]
          if (currentChannel.channelId) {
            this.delConfigedChannel(currentChannel, index)
          } else {
            this.formData.segmentChannelList.splice(index, 1)
          }
        }
      },
      // 校验网段通道是否有例测任务和任务状态
      async delConfigedChannel(channelData, index) {
        const portData = [channelData.startPortId, channelData.endPortId]
        const res = await linkTestPlan.portTestStatus(portData)
        let msg = ''
        const option = {
          type: 'warning',
          confirmButtonText: this.$t('YES'),
          cancelButtonText: this.$t('CLOSE'),
          showConfirmButton: false
        }
        // 提示优先级1.PROCESS("进行中")；2.READY("准备")；3.PLAN("计划")
        if (portData.some(i => res[i] === 'PROCESS')) {
          msg = this.$t('PROCESS_CAN_NOT_DELETE', { msg: this.$t('CHANNEL') })
        } else if (portData.some(i => res[i] === 'READY')) {
          msg = this.$t('READY_CONFIRM_DELETE', { msg: this.$t('CHANNEL') })
        } else if (portData.some(i => res[i] === 'PLAN')) {
          msg = this.$t('PLAN_CONFIRM_DELETE', { msg: this.$t('CHANNEL') })
        } else {
          this.formData.segmentChannelList.splice(index, 1)
          return
        }
        this.$confirm(msg, option)
          .then(() => {
            this.formData.segmentChannelList.splice(index, 1)
          })
          .catch(() => {})
      },
      // 获取端口列表
      getPortList(nodeId, type) {
        this.showChannelList = false
        let selectedPort = []
        this[`${type}PortList`] = []
        // console.log('this.formData', this.formData)

        // 查看、修改情况需要把已选数据拼接上去
        if (this.type !== 'add') {
          selectedPort = this.formData.segmentChannelList.map(i =>
            type === 'a' ? i.startPortId : i.endPortId
          )
        }
        // AOCC和集群设备端口单独获取
        const nodeSide = type === 'a' ? 'startNode' : 'endNode'
        if (this.formData[nodeSide].nodeType === 'CLUSTER') {
          clusterApi.extPortList({ clusterId: nodeId }).then(res => {
            this.getAfsPort(res, type, selectedPort)
          })
        } else {
          nodeApi
            .portList({
              nodeId: nodeId,
              status: null
            })
            .then(res => {
              this.getAfsPort(res, type, selectedPort)
            })
        }
      },
      // 返回结果格式化
      getAfsPort(res, type, selectedPort) {
        res = res || []
        // 替换国际化标识，和对端端口名称
        res.forEach(i => {
          i.bizName = this.$utils.handleServiceI18n(i.bizName)
          const connPort = res.find(j => j.portId === i.connPortId)
          i.connPortName = connPort ? this.$utils.handleServiceI18n(connPort.bizName) : '--'
        })
        // 光分器只能选择输入
        if (res[0] && res[0].deviceType === 'LIGHT_SPLIT') {
          res = [res[0]]
        }
        this[`${type}AllPortList`] = res
        this[`${type}PortList`] = res.filter(
          i => i.status === 'IDLE' || selectedPort.includes(i.portId)
        )
      },
      // 获取空闲纤芯编号
      getCableFiberList() {
        if (!this.formData.cableId || this.type === 'view') return
        let selectedCable = []
        // 查看、修改情况需要把已选数据拼接上去
        if (this.type !== 'add') {
          selectedCable = this.formData.segmentChannelList.map(i => i.fiber || {})
        }
        this.cableFiberList = [...selectedCable]
        CableFiberApi.idleList({
          cableId: this.formData.cableId
        }).then(res => {
          this.cableFiberList = [
            ...selectedCable.filter(i => !res.some(j => j.fiberId === i.fiberId)),
            ...res
          ]
        })
      },
      // 获取区域/站点/机房
      getRegionName(stationId) {
        const stationData = this.baseRegionList.find(i => i.regionId === stationId)
        return stationData ? stationData.regionName : ''
      },
      portChange(row, side) {
        const portList = side === 'start' ? this.aPortList : this.zPortList
        const portData = portList.find(i => row[side + 'PortId'] === i.portId)
        row[side + 'Port'] = portData
      },
      fiberChange(row) {
        const fiberData = this.cableFiberList.find(i => row.fiberId === i.fiberId)
        row.fiber = fiberData
      },
      addLog(actionType = 'import') {
        let terminal = 'VIEW_SEGMENT_EXPORT'
        let i18nKey = 'VIEW_SEGMENT_EXPORT_LOG'
        if (this.type === 'add') {
          terminal = actionType === 'import' ? 'ADD_SEGMENT_IMPORT' : 'ADD_SEGMENT_EXPORT'
          i18nKey = actionType === 'import' ? 'ADD_SEGMENT_IMPORT_LOG' : 'ADD_SEGMENT_EXPORT_LOG'
        } else {
          terminal = actionType === 'import' ? 'MODIFY_SEGMENT_IMPORT' : 'MODIFY_SEGMENT_EXPORT'
          i18nKey = actionType === 'import' ? 'MODIFY_SEGMENT_IMPORT_LOG' : 'MODIFY_SEGMENT_EXPORT_LOG'
        }
        const params = {
          api: '',
          item: 'MENU_SEGMENT_MANAGER', // 网段管理
          terminal: terminal,
          object: this.type === 'add' ? '/' : this.formData.segmentName,
          operateResult: true,
          realName: this.getUser.realName,
          content: JSON.stringify({
            segmentName: this.formData.segmentName,
            currentUserId: this.getUserId,
            i18nKey: i18nKey
          })
        }
        // 记录操作日志
        OperateLogApi.addLog(params)
      }
    }
  }
</script>

<style lang="scss">
  .text-warning {
    font-size: 12px;
    vertical-align: bottom;
  }

  .select-holder {
    padding: 0 5px 0 15px;
    width: 100%;
    height: 28px;
    font-size: 12px;
    text-align: left;
    line-height: 26px;
    // white-space: nowrap;
  white-space: pre;
    overflow: hidden;
    text-overflow: clip;
    border: 1px solid #eee;
    border-radius: 3px;
    cursor: pointer;
    box-sizing: border-box;

    &.disabled {
      cursor: no-drop;
    }

    i {
      width: 25px;
      line-height: 26px;
      color: #c0c4cc;
    }
  }

  #selectDiv {
    position: fixed;
    padding: 0 10px;
    will-change: top, left, width;
    z-index: 2;
  }
  .segment-detail {
    .w-50 {
      display: flex;
      align-items: baseline;
      padding-right: 20px;
      .title-label {
        white-space: nowrap;
      }
    }
  }
</style>
